// ClickedPints.js (c) 2012 matsuda
// Vertex shader program
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'attribute vec4 a_Color;\n' +
  'uniform mat4 u_matrix;\n' +
  'varying vec4 v_Color;\n' +
  'void main() {\n' +
  '  gl_Position =  u_matrix * a_Position;\n' +
  '  v_Color =  a_Color;\n' +
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
'precision mediump float;\n' +
  'varying vec4 v_Color;\n' +
  'void main() {\n' +
  '  gl_FragColor = v_Color;\n' +
  '}\n';

function main() {
  // Retrieve <canvas> element
  var canvas = document.getElementById('webgl');

  // Get the rendering context for WebGL
  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for WebGL');
    return;
  }

  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }

  var verticesPosition = new Float32Array([
      0.0,0.5,-0.5,-0.5,0.5,-0.5
    ]);

  var verticesColor = new Float32Array([
      1.0,0.0,0.0,
      0.0,1.0,0.0,
      0.0,0.0,1.0
    ]);

  var verticesPositionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER,verticesPositionBuffer);
  gl.bufferData(gl.ARRAY_BUFFER,verticesPosition,gl.STATIC_DRAW);

  // // Get the storage location of a_Position
  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if (a_Position < 0) {
    console.log('Failed to get the storage location of a_Position');
    return;
  }
  gl.vertexAttribPointer(a_Position,2,gl.FLOAT,false,0,0);
  gl.enableVertexAttribArray(a_Position);

  var verticesColorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER,verticesColorBuffer);
  gl.bufferData(gl.ARRAY_BUFFER,verticesColor,gl.STATIC_DRAW);

  var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
  if (a_Color < 0) {
    console.log('Failed to get the storage location of a_Color');
    return;
  }


  gl.vertexAttribPointer(a_Color,3,gl.FLOAT,false,0,0);
  gl.enableVertexAttribArray(a_Color);

  var angle = 0;
  var dir = new Float32Array([0.0,0.0,0.0,0.0]);

  var cosB = Math.cos(angle);
  var sinB = Math.sin(angle);

  var matrix = new Float32Array([
      cosB,sinB,0.0,0.0,
      -sinB,cosB,0.0,0.0,
      0.0,0.0,1.0,0.0,
      dir[0],dir[1],dir[2],1.0
    ]);

  var u_matrix = gl.getUniformLocation(gl.program,'u_matrix');

  gl.uniformMatrix4fv(u_matrix,false,matrix)

  // Specify the color for clearing <canvas>
  gl.clearColor(0.0, 0.0, 0.0, 1.0);

  // Clear <canvas>
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, 3);
}
